package cn.lyq.card.ui.home

import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.base.BaseFg
import cn.lyq.card.data.model.BannerInfo
import cn.lyq.card.data.model.HomeInfo
import cn.lyq.card.data.model.WalletInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.ui.device.DeviceListActivity
import cn.lyq.card.ui.income.IncomeDetailActivity
import cn.lyq.card.ui.order.OrderListActivity
import cn.lyq.card.ui.realname.RealNameAuthFg
import cn.lyq.card.ui.share.ShareListActivity
import cn.lyq.card.ui.statistics.StatisticsAllActivity
import cn.lyq.card.ui.web.WebActivity
import cn.lyq.card.utils.hasIndex
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.toMoney
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.android.synthetic.main.fg_home.*
import kotlinx.android.synthetic.main.layout_home.*
import kotlinx.android.synthetic.main.layout_title.*
import java.util.*


class HomeFg : BaseFg() {

    private val mModel by lazy {
        getVM(HomeVM::class.java)
    }
    private var isFristIn = true

    override fun getLayoutId(): Int {
        return R.layout.fg_home
    }

    override fun initView(view: View) {
        super.initView(view)
        tvTitleSplit.visibility = View.GONE
        imgBack.visibility = View.GONE
        tvTitle.setText(R.string.app_name)
    }

    private fun setBanner(images: MutableList<BannerInfo>) {
        banner.addBannerLifecycleObserver(this).adapter =
            object : BannerImageAdapter<BannerInfo>(images) {
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: BannerInfo?,
                    position: Int,
                    size: Int
                ) {
                    holder?.imageView?.loadUrl(data?.image)
                }
            }
        banner.setOnBannerListener { _, position ->
            val target = images.takeIf { it.hasIndex(position) }?.get(position)?.url ?: ""
            if (target.isNotEmpty()) {
                WebActivity.start(requireContext(), target)
            }
        }
    }

    override fun initListener(view: View) {
        super.initListener(view)
        tvInviteAgent.setClick {
            startActivity(ShareListActivity::class.java)
        }
        tvDeviceBuy.setClick {
            startActivity(DeviceListActivity::class.java)
        }
        tvDeviceStatistics.setClick {
            startActivity(StatisticsAllActivity::class.java)
        }
        tvMyOrder.setClick {
            startActivity(OrderListActivity::class.java)
        }
        refreshLayout.setOnRefreshListener {
            refreshHomeInfo()
        }
        tvCheckDetail.setClick {
            IncomeDetailActivity.start(requireContext(), 0, Calendar.getInstance())
        }
    }

    override fun onResume() {
        super.onResume()
        refreshHomeInfo()
    }

    private fun refreshHomeInfo() {
        mModel.refreshHomeInfo().observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> {
                    val userInfo = it.requireData().userInfo?.apply {
                        this.isSetWithdrawalPassword = it.requireData().isSetWithdrawalPassword
                        this.idCardStatus = it.requireData().idCardStatus
                    }
                    UserManager.post(userInfo)
                    setData(it.requireData())
                    refreshLayout.isRefreshing = false
                }
                Status.ERROR -> {
                    refreshLayout.isRefreshing = false
                    ToastUtils.showShort(it.message.getMsg())
                }
                Status.LOADING -> {
                    if (!refreshLayout.isRefreshing) {
                        refreshLayout.isRefreshing = true
                    }
                }
            }
        })
    }

    private fun setData(info: HomeInfo) {
        setBanner(info.banner)
        tvTransactionAmount.text = info.volume.toMoney()
        tvDeviceActive.text = info.actCount.toString()
        tvTeamTransactionAmount.text = info.teamVolume.toMoney()
        tvTeamDeviceActive.text = info.actTeamCount.toString()
        tvTodayIncomeAmount.text = info.todayProfit.toMoney()
        SpanUtils.with(tvYesterdayIncomeAmount)
            .append("昨日总收益：")
            .setForegroundColor(ContextCompat.getColor(requireContext(), R.color.font_gray))
            .append(info.yesterdayProfit.toMoney())
            .create()
        SpanUtils.with(tvTodayNewStore)
            .append(info.todayAddMerchantCount.toString())
            .setFontSize(resources.getDimensionPixelSize(R.dimen.font17), false)
            .setBold()
            .append("人")
            .create()
        SpanUtils.with(tvTodayNewAgent)
            .append(info.todayAddUserCount.toString())
            .setFontSize(resources.getDimensionPixelSize(R.dimen.font17), false)
            .setBold()
            .append("人")
            .create()

        UserManager.unreadNotice.postValue(info.unreadNotice)
        if (isFristIn) {
            isFristIn = false
            if (info.idCardStatus == 3 || info.idCardStatus == 2) {
                val requireActivity = requireActivity()
                if (requireActivity is BaseActivity) {
                    RealNameAuthFg().show(requireActivity)
                }
            }
        }
    }

    @BusUtils.Bus(tag = BusTag.REFRESH_BALANCE, threadMode = BusUtils.ThreadMode.MAIN)
    fun refreshBalance() {
        refreshHomeInfo()
    }

}